import React, { useContext } from "react";
import { useEffect, useState } from "react";
import getConfig from "next/config";
import Link from "next/link";
import { useRouter } from "next/router";
import { withAuthServerSideProps } from "../utils/withAuth";
import Box from "../components/Box";
import Text from "../components/Text";
import SEO from "../components/SEO";
import TorrentList from "../components/TorrentList";
import Infobox from "../components/Infobox";
import { ErrorCircle } from "@styled-icons/boxicons-regular/ErrorCircle";
import { News } from "@styled-icons/boxicons-regular/News";
import moment from "moment/moment";
import LocaleContext from "../utils/LocaleContext";
import Recommendations from "../components/Recommendations";
import OnboardingGuide from "../components/OnboardingGuide";
import Button from "../components/Button";

const PublicLanding = ({ name, allowRegister }) => {
  const { getLocaleString } = useContext(LocaleContext);
  return (
    <Box
      minHeight="calc(100vh - 173px)"
      display="flex"
      alignItems="center"
      justifyContent="center"
      flexDirection="column"
    >
      <Text as="h1" fontSize={6} textAlign="center" lineHeight={1.2}>
        {name}
      </Text>
      <Box display="flex" mt={4}>
        <Box>
          <Link href="/login">
            <a>{getLocaleString("logIn")}</a>
          </Link>
        </Box>
        {allowRegister && (
          <Box ml={4}>
            <Link href="/register">
              <a>{getLocaleString("register")}</a>
            </Link>
          </Box>
        )}
      </Box>
    </Box>
  );
};

const Index = ({
  token,
  latestTorrents,
  latestAnnouncement,
  emailVerified,
  isFirstLogin = false,
}) => {
  const {
    publicRuntimeConfig: {
      SQ_SITE_NAME,
      SQ_ALLOW_REGISTER,
      SQ_TORRENT_CATEGORIES,
    },
  } = getConfig();

  const router = useRouter();
  const [showOnboarding, setShowOnboarding] = useState(false);
  const [showTempMessage, setShowTempMessage] = useState(false);
  const { getLocaleString } = useContext(LocaleContext);

  // 检查是否需要显示新手引导
  useEffect(() => {
    // 如果是首次登录或从注册页面过来，显示引导
    if (isFirstLogin || router.query.newUser === "true") {
      console.log("首次登录或新用户，显示引导");
      setShowOnboarding(true);
    }
  }, [isFirstLogin, router.query]);

  // 监控 showOnboarding 状态变化
  useEffect(() => {
    console.log("showOnboarding 状态变化:", showOnboarding);
  }, [showOnboarding]);

  // 显示临时消息
  const showMessage = () => {
    setShowTempMessage(true);
    setTimeout(() => setShowTempMessage(false), 3000);
  };

  if (!token)
    return (
      <>
        <SEO />
        <PublicLanding name={SQ_SITE_NAME} allowRegister={SQ_ALLOW_REGISTER} />
      </>
    );

  const handleSearch = (e) => {
    e.preventDefault();
    const form = new FormData(e.target);
    const query = form.get("query");
    if (query) router.push(`/search/${encodeURIComponent(query)}`);
  };

  return (
    <>
      <SEO title={getLocaleString("navHome")} />
      <Box
        display="flex"
        justifyContent="space-between"
        alignItems="center"
        mb={5}
      >
        <Text as="h1">{getLocaleString("navHome")}</Text>
        {token && (
          <Button
            variant="outline"
            size="sm"
            onClick={() => {
              console.log("新手引导按钮被点击");
              setShowOnboarding(true);
            }}
          >
            查看新手指南
          </Button>
        )}
      </Box>

      {/* 显示新手引导 */}
      {showOnboarding && (
        <OnboardingGuide
          isFirstLogin={isFirstLogin}
          onClose={() => setShowOnboarding(false)}
        />
      )}

      {showTempMessage && (
        <Box
          position="fixed"
          top="20px"
          right="20px"
          bg="primary"
          color="white"
          p={3}
          borderRadius={2}
          zIndex={9999}
        >
          按钮点击成功！请检查控制台日志。
        </Box>
      )}

      {!emailVerified && (
        <Infobox mb={5}>
          <Text icon={ErrorCircle} iconColor="error">
            {getLocaleString("indexText1")}
          </Text>
        </Infobox>
      )}
      {latestAnnouncement && (
        <Link href={`/announcements/${latestAnnouncement.slug}`} passHref>
          <Box
            as="a"
            _css={{
              "&:hover": {
                textDecoration: "none",
              },
            }}
          >
            <Infobox mb={5}>
              <Text
                icon={News}
                iconColor="primary"
                color="grey"
                fontWeight={600}
                fontSize={1}
                _css={{ textTransform: "uppercase" }}
                mb={3}
              >
                {getLocaleString("indexLatestAnnounce")}
              </Text>
              <Text as="h2" fontSize={3} mb={3}>
                {latestAnnouncement.title}
              </Text>
              <Text color="grey">
                {getLocaleString("reqPosted")}{" "}
                {moment(latestAnnouncement.created).format(
                  `${getLocaleString("indexTime")}`
                )}{" "}
                {getLocaleString("reqBy")}{" "}
                {latestAnnouncement.createdBy?.username ? (
                  <Link
                    href={`/user/${latestAnnouncement.createdBy.username}`}
                    passHref
                  >
                    <a>{latestAnnouncement.createdBy.username}</a>
                  </Link>
                ) : (
                  "deleted user"
                )}
              </Text>
            </Infobox>
          </Box>
        </Link>
      )}

      {token && (
        <div className="recommendation-section">
          <div className="recommendation-section">
            <Recommendations token={token} count={3} />
          </div>
        </div>
      )}

      <Text as="h2" mb={4}>
        {getLocaleString("indexLatestTorrents")}
      </Text>
      <div className="torrent-list-section">
        <TorrentList
          torrents={latestTorrents}
          categories={SQ_TORRENT_CATEGORIES}
        />
      </div>
    </>
  );
};

export const getServerSideProps = withAuthServerSideProps(
  async ({ token, fetchHeaders }) => {
    if (!token) return { props: {} };

    const {
      publicRuntimeConfig: { SQ_API_URL },
    } = getConfig();

    try {
      const latestTorrentsRes = await fetch(`${SQ_API_URL}/torrent/latest`, {
        headers: fetchHeaders,
      });
      if (
        latestTorrentsRes.status === 403 &&
        (await latestTorrentsRes.text()) === "User is banned"
      ) {
        throw "banned";
      }
      const latestTorrents = await latestTorrentsRes.json();

      const latestAnnouncementRes = await fetch(
        `${SQ_API_URL}/announcements/latest`,
        {
          headers: fetchHeaders,
        }
      );
      let latestAnnouncement = null;
      if (latestAnnouncementRes.status === 200) {
        latestAnnouncement = await latestAnnouncementRes.json();
      }

      const verifiedRes = await fetch(`${SQ_API_URL}/account/get-verified`, {
        headers: fetchHeaders,
      });

      // 获取用户信息，检查是否首次登录
      const userRes = await fetch(`${SQ_API_URL}/account/info`, {
        headers: fetchHeaders,
      });

      let isFirstLogin = false;
      if (userRes.status === 200) {
        const userData = await userRes.json();
        // 检查用户创建时间是否在24小时内且从未完成过引导
        const userCreatedTime = new Date(userData.created).getTime();
        const oneDayAgo = new Date().getTime() - 24 * 60 * 60 * 1000;
        isFirstLogin =
          userCreatedTime > oneDayAgo && !userData.onboardingCompleted;
      }

      return {
        props: {
          latestTorrents,
          latestAnnouncement,
          emailVerified: await verifiedRes.json(),
          isFirstLogin, // 传递首次登录状态
        },
      };
    } catch (e) {
      console.error(e);
      if (e === "banned") throw "banned";
      return { props: {} };
    }
  },
  false,
  true
);

export default Index;
